package com.donfelix.looknews.view.adapter;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorMatrixColorFilter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.donfelix.looknews.R;
import com.donfelix.looknews.bean.zhihu.ZhihuDailyItem;
import com.donfelix.looknews.common.Config;
import com.donfelix.looknews.util.DBUtils;
import com.donfelix.looknews.util.DensityUtil;
import com.donfelix.looknews.util.DribbbleTarget;
import com.donfelix.looknews.util.ObservableColorMatrix;
import com.donfelix.looknews.view.implview.OnLoadingMoreListener;
import com.donfelix.looknews.view.implview.OnRecyclerViewItemClickLinstener;
import com.donfelix.looknews.widget.AutoScrollViewPager;
import com.donfelix.looknews.widget.BadgedFourThreeImageView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Don on 2017/3/29.
 * Desc
 */

public class ZhihuAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements OnLoadingMoreListener {

    private static final int TYPE_LOADING_MORE = -1;
    private static final int TYPE_NOMAL_ITEM = 1;
    private static final int TYPE_BANNER_HEAD = 0;
    private int headerCount = 1;
    private Context context;
    private boolean showLoadingMore;
    private String image_url;
    private float width;
    private int widthPx;
    private int heightPx;
    private List<ZhihuDailyItem> datas = new ArrayList<>();
    private List<ZhihuDailyItem> bannerDatas = new ArrayList<>();
    private OnRecyclerViewItemClickLinstener recyclerViewItemClickLinstener;

    public void setOnRecyclerViewItemClickLinstener(OnRecyclerViewItemClickLinstener linstener) {
        this.recyclerViewItemClickLinstener = linstener;
    }

    public ZhihuAdapter(Context context) {
        this.context = context;
        width = context.getResources().getDimension(R.dimen.image_width);
        widthPx = DensityUtil.dip2px(context, width);
        heightPx = widthPx * 3 / 4;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_LOADING_MORE:
                View loadingMore = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false);
                return new LoaddingMoreViewHolder(loadingMore);
            case TYPE_NOMAL_ITEM:
                View normalItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_zhihu_daily_item, parent, false);
                return new ZhihuViewHolder(normalItem);
            case TYPE_BANNER_HEAD:
                View bannerHeader = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_banner_headview, parent, false);
                return new BannerHeaderViewHolder(bannerHeader);
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int type = getItemViewType(position);
        switch (type) {
            case TYPE_LOADING_MORE:
                bindLoadingMoreViewHolder((LoaddingMoreViewHolder) holder, position);
                break;
            case TYPE_NOMAL_ITEM:
                bindNormalItemViewHolder((ZhihuViewHolder) holder, position - 1);
                break;
            case TYPE_BANNER_HEAD:
                bindBannerHeaderViewHolder((BannerHeaderViewHolder) holder, position);
                break;
            default:
                break;
        }
    }

    private void bindLoadingMoreViewHolder(LoaddingMoreViewHolder holder, int position) {
        holder.progressBar.setVisibility(showLoadingMore == true ? View.VISIBLE : View.GONE);
    }

    private void bindBannerHeaderViewHolder(final BannerHeaderViewHolder holder, int position) {
        List<String> imageUrls = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        List<ImageView> dots = new ArrayList<>();
        holder.llPoints.removeAllViews();
        int size = bannerDatas.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                ZhihuDailyItem dailyItem = bannerDatas.get(i);
                String image = dailyItem.getImage();
                String title = dailyItem.getTitle();
                ImageView dot = new ImageView(context);
                dot.setImageResource(R.drawable.dot_normal);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(context, 8), DensityUtil.dip2px(context, 8));
                if (i != 0) {
                    params.leftMargin = DensityUtil.dip2px(context, 8);
                }
                dot.setLayoutParams(params);
                holder.llPoints.addView(dot);
                imageUrls.add(image);
                titles.add(title);
                dots.add(dot);
            }
        }
        holder.viewPager.setImageUrls(imageUrls);
        holder.viewPager.setTitles(titles, holder.title);
        holder.viewPager.setDots(dots, holder.dotFucus);
        holder.viewPager.start();
        holder.viewPager.setOnItemClickListener(new AutoScrollViewPager.OnItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                if (recyclerViewItemClickLinstener != null) {
                    recyclerViewItemClickLinstener.onItemClick(holder, bannerDatas.get(pos));
                }
            }
        });
    }

    private void bindNormalItemViewHolder(final ZhihuViewHolder holder, int position) {
        final ZhihuDailyItem dailyItem = datas.get(position);
        //ZhihuDailyItem dailyItem = datas.get(holder.getAdapterPosition());
        if (DBUtils.getDB(context).isRead(Config.ZHIHU, dailyItem.getId(), 1)) {
            holder.text.setTextColor(Color.GRAY);
        } else {
            holder.text.setTextColor(Color.BLACK);
        }
        holder.text.setText(dailyItem.getTitle());
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recyclerViewItemClickLinstener != null) {
                    recyclerViewItemClickLinstener.onItemClick(holder, dailyItem);
                }
            }
        });
        holder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recyclerViewItemClickLinstener != null) {
                    recyclerViewItemClickLinstener.onItemClick(holder, dailyItem);
                }
            }
        });
        Glide.with(context)
                .load(dailyItem.getImages()[0])
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        if (!dailyItem.hasFadeIn) {
                            holder.image.setHasTransientState(true);
                            final ObservableColorMatrix cm = new ObservableColorMatrix();
                            final ObjectAnimator animator = ObjectAnimator.ofFloat(cm, ObservableColorMatrix.SATURATION, 0f, 1f);
                            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                @Override
                                public void onAnimationUpdate(ValueAnimator animation) {
                                    holder.image.setColorFilter(new ColorMatrixColorFilter(cm));
                                }
                            });
                            animator.setDuration(2000L);
                            animator.setInterpolator(new AccelerateInterpolator());
                            animator.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    super.onAnimationEnd(animation);
                                    holder.image.clearColorFilter();
                                    holder.image.setHasTransientState(false);
                                    animator.start();
                                    dailyItem.hasFadeIn = true;
                                }
                            });
                        }
                        return false;
                    }
                }).diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .centerCrop()
                .override(widthPx, heightPx)
                .into(new DribbbleTarget(holder.image, false));
    }

    @Override
    public int getItemCount() {
        return datas == null ? headerCount : datas.size() + headerCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (position < headerCount) {
            return TYPE_BANNER_HEAD;
        } else if (position >= getItemCount()) {
            return TYPE_LOADING_MORE;
        } else {
            return TYPE_NOMAL_ITEM;
        }
    }

    public void addItems(List<ZhihuDailyItem> items) {
        if (items == null) {
            return;
        }
        datas.addAll(items);
        notifyDataSetChanged();
    }

    public void addBannerItems(List<ZhihuDailyItem> items) {
        if (items == null) {
            return;
        }
        bannerDatas.addAll(items);
        notifyDataSetChanged();
    }

    public void clearData() {
        datas.clear();
        bannerDatas.clear();
        notifyDataSetChanged();
    }

    @Override
    public void loadingStart() {
        if (showLoadingMore) {
            return;
        }
        showLoadingMore = true;
        notifyItemInserted(getLoadingMoreItemPosition());
    }

    @Override
    public void loadingFinished() {
        if (showLoadingMore) {
            return;
        }
        int loadingPosition = getLoadingMoreItemPosition();
        showLoadingMore = false;
        notifyItemRemoved(loadingPosition);
    }

    private int getLoadingMoreItemPosition() {
        return showLoadingMore ? getItemCount() - 1 : RecyclerView.NO_POSITION;
    }

    public class ZhihuViewHolder extends RecyclerView.ViewHolder {
        private LinearLayout linearLayout;
        private BadgedFourThreeImageView image;
        public TextView text;

        public ZhihuViewHolder(View itemView) {
            super(itemView);
            linearLayout = (LinearLayout) itemView.findViewById(R.id.zhihu_item_layout);
            image = (BadgedFourThreeImageView) itemView.findViewById(R.id.item_image_id);
            text = (TextView) itemView.findViewById(R.id.item_text_id);
        }
    }

    public class LoaddingMoreViewHolder extends RecyclerView.ViewHolder {
        private ProgressBar progressBar;

        public LoaddingMoreViewHolder(View itemView) {
            super(itemView);
            progressBar = (ProgressBar) itemView.findViewById(R.id.loading);
            //progressBar = (ProgressBar) itemView;
        }
    }

    public class BannerHeaderViewHolder extends RecyclerView.ViewHolder {
        private AutoScrollViewPager viewPager;
        private TextView title;
        private LinearLayout llPoints;
        private ImageView dotFucus;

        public BannerHeaderViewHolder(View itemView) {
            super(itemView);
            viewPager = (AutoScrollViewPager) itemView.findViewById(R.id.viewpager);
            title = (TextView) itemView.findViewById(R.id.title);
            llPoints = (LinearLayout) itemView.findViewById(R.id.ll_point);
            dotFucus = (ImageView) itemView.findViewById(R.id.dot_focused);
        }
    }
}
